<?php

if(!defined('IN_UCHOME')) {
	exit('Access Denied');
}
include_once(S_ROOT.'./source/function_cp.php');

function retrieve_login_form()
{
    global $_SGLOBAL;

    ob_start();
    include_once template('site/tpl/login');
    $bgcontent = ob_get_contents();
    ob_end_clean();

    $r['html']=$bgcontent;
    return $r;
    //exit;
}

function show_ajax_dialog($tmp_file, $arr_key = 'html')
{
	 global $_SGLOBAL;
	 
	 ob_start();
     include_once template('site/tpl/' . $tmp_file);
     $bgcontent = ob_get_contents();
     ob_end_clean();

     $r[$arr_key]=$bgcontent;
     return json_encode($r);
	// exit;
}



define("OP_TO_FILE", 1);              // Output to file
define("OP_OUTPUT", 2);               // Output to browser
define("OP_NOT_KEEP_SCALE", 4);       // Free scale
define("OP_BEST_RESIZE_WIDTH", 8);    // Scale to width
define("OP_BEST_RESIZE_HEIGHT", 16);  // Scale to height

define("CM_DEFAULT",0);               // Clipping method: default
define("CM_LEFT_OR_TOP",1);           // Clipping method: left or top
define("CM_MIDDLE",2);                // Clipping method: middle
define("CM_RIGHT_OR_BOTTOM",3);       // Clipping method: right or bottom

function wresize($srcFile, $dstFile, $dstW, $dstH, $option=OP_TO_FILE, $cutmode=CM_DEFAULT, $startX=0, $startY=0) {
		$img_type = array(1=>"gif", 2=>"jpeg", 3=>"png");
		$type_idx = array("gif"=>1, "jpg"=>2, "jpeg"=>2, "jpe"=>2, "png"=>3);

		if (!file_exists($srcFile)) {
			return array(-1, "Source file not exists: $srcFile.");
		}

		$path_parts = @pathinfo($dstFile);
		$ext = strtolower ($path_parts["extension"]);
	
		if ($ext == "") {
			return array(-5, "Can't detect output image's type.");
		}
	
		$func_output = "image" . $img_type[$type_idx[$ext]];
	
		if (!function_exists ($func_output)) {
			return array(-2, "Function not exists for output：$func_output.");
		}
	
		$data = @GetImageSize($srcFile);
		$func_create = "imagecreatefrom" . $img_type[$data[2]];
	
		if (!function_exists ($func_create)) {
			return array(-3, "Function not exists for create：$func_create.");
		}
	
		$im = @$func_create($srcFile);
	
		$srcW = @ImageSX($im);
		$srcH = @ImageSY($im);
		$srcX = 0;
		$srcY = 0;
		$dstX = 0;
		$dstY = 0;
	
		if ($option & OP_BEST_RESIZE_WIDTH) {
			$dstH = round($dstW * $srcH / $srcW);
		}
	
		if ($option & OP_BEST_RESIZE_HEIGHT) {
			$dstW = round($dstH * $srcW / $srcH);
		}
	
		$fdstW = $dstW;
		$fdstH = $dstH;
	
		if ($cutmode != CM_DEFAULT) { // clipping method 1: left or top 2: middle 3: right or bottom
	
			$srcW -= $startX;
			$srcH -= $startY;
	
			if ($srcW*$dstH > $srcH*$dstW) { 
				$testW = round($dstW * $srcH / $dstH);
				$testH = $srcH;
			} else {
				$testH = round($dstH * $srcW / $dstW);
				$testW = $srcW;
			}
			
			switch ($cutmode) {
				case CM_LEFT_OR_TOP: $srcX = 0; $srcY = 0; break;
				case CM_MIDDLE: $srcX = round(($srcW - $testW) / 2);
								$srcY = round(($srcH - $testH) / 2); break;
				case CM_RIGHT_OR_BOTTOM: $srcX = $srcW - $testW;
										 $srcY = $srcH - $testH;
			}
	
			$srcW = $testW;
			$srcH = $testH;
			$srcX += $startX;
			$srcY += $startY;
	
		} else {
			if (!($option & OP_NOT_KEEP_SCALE)) {
				if ($srcW*$dstH>$srcH*$dstW) { 
					$fdstH=round($srcH*$dstW/$srcW); 
					$dstY=floor(($dstH-$fdstH)/2); 
					$fdstW=$dstW;
				} else { 
					$fdstW=round($srcW*$dstH/$srcH); 
					$dstX=floor(($dstW-$fdstW)/2); 
					$fdstH=$dstH;
				}
	
				$dstX=($dstX<0)?0:$dstX;
				$dstY=($dstX<0)?0:$dstY;
				$dstX=($dstX>($dstW/2))?floor($dstW/2):$dstX;
				$dstY=($dstY>($dstH/2))?floor($dstH/s):$dstY;
	
			}
		}
	
		if( function_exists("imagecopyresampled") and 
			function_exists("imagecreatetruecolor") ){
			$func_create = "imagecreatetruecolor";
			$func_resize = "imagecopyresampled";
		} else {
			$func_create = "imagecreate";
			$func_resize = "imagecopyresized";
		}
	
		$newim = @$func_create($dstW,$dstH);
		$black = @ImageColorAllocate($newim, 0,0,0);
		$back = @imagecolortransparent($newim, $black);
		@imagefilledrectangle($newim,0,0,$dstW,$dstH,$black);
		@$func_resize($newim,$im,$dstX,$dstY,$srcX,$srcY,$fdstW,$fdstH,$srcW,$srcH);
	
		if ($option & OP_TO_FILE) {
			switch ($type_idx[$ext]) {
				case 1:
				case 3:
					@$func_output($newim,$dstFile);
					break;
				case 2:
					@$func_output($newim,$dstFile,100);
					break;
			}
		}
	
		if ($option & OP_OUTPUT) {
			if (function_exists("headers_sent")) {
				if (headers_sent()) {
					return array(-4, "HTTP already sent, can't output image to browser.");
				}
			}
			header("Content-type: image/" . $img_type[$type_idx[$ext]]);
			@$func_output($newim);
		}
	
		@imagedestroy($im);
		@imagedestroy($newim);
	
		return array(0, "OK");
	}

/**/

//生成缩略图
function wp_makethumb($srcfile) {
	global $_SGLOBAL;

	//判断文件是否存在
	if (!file_exists($srcfile)) {
		return '';
	}

	$r_dstfile = $srcfile;

    $dstfile  = $srcfile.'.160.jpg';
    wresize($srcfile, $dstfile, 160, 160, 1|4, 2);

	$dstfile  = $srcfile.'.65.jpg';
	wresize($srcfile, $dstfile, 65, 65, 1|4, 2);

	return $r_dstfile;

	/*
	$dstfile = $srcfile.'.thumb.jpg';
	
    $tow = 100;
    $toh = 100;

	$make_max = 0;
	$maxtow = 600;
	$maxtoh = 600;
	if($maxtow >= 300 && $maxtoh >= 300) {
		$make_max = 1;
	}

	//获取图片信息
	$im = '';
	if($data = getimagesize($srcfile)) {
		if($data[2] == 1) {
			$make_max = 0;//gif不处理
			if(function_exists("imagecreatefromgif")) {
				$im = imagecreatefromgif($srcfile);
			}
		} elseif($data[2] == 2) {
			if(function_exists("imagecreatefromjpeg")) {
				$im = imagecreatefromjpeg($srcfile);
			}
		} elseif($data[2] == 3) {
			if(function_exists("imagecreatefrompng")) {
				$im = imagecreatefrompng($srcfile);
			}
		}
	}
	if(!$im) return '';
	
	$srcw = imagesx($im);
	$srch = imagesy($im);
	
	$towh = $tow/$toh;
	$srcwh = $srcw/$srch;
	if($towh <= $srcwh){
		$ftow = $tow;
		$ftoh = $ftow*($srch/$srcw);
		
		$fmaxtow = $maxtow;
		$fmaxtoh = $fmaxtow*($srch/$srcw);
	} else {
		$ftoh = $toh;
		$ftow = $ftoh*($srcw/$srch);
		
		$fmaxtoh = $maxtoh;
		$fmaxtow = $fmaxtoh*($srcw/$srch);
	}
	if($srcw <= $maxtow && $srch <= $maxtoh) {
		$make_max = 0;//不处理
	}
	if($srcw > $tow || $srch > $toh) {
		if(function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$ni = imagecreatetruecolor($ftow, $ftoh)) {
			imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
			//大图片
			if($make_max && @$maxni = imagecreatetruecolor($fmaxtow, $fmaxtoh)) {
				imagecopyresampled($maxni, $im, 0, 0, 0, 0, $fmaxtow, $fmaxtoh, $srcw, $srch);
			}
		} else {
			return '';
		}
		if(function_exists('imagejpeg')) {
			imagejpeg($ni, $dstfile);
			//大图片
			if($make_max) {
				imagejpeg($maxni, $srcfile);
			}
		} elseif(function_exists('imagepng')) {
			imagepng($ni, $dstfile);
			//大图片
			if($make_max) {
				imagepng($maxni, $srcfile);
			}
		}
		imagedestroy($ni);
		if($make_max) {
			imagedestroy($maxni);
		}
	}
	imagedestroy($im);

	if(!file_exists($dstfile)) {
		return '';
	} else {
		return $dstfile;
	}
	*/


}

function save_prof_avatar($FILE, $profid) {
	global $_SGLOBAL, $_SCONFIG, $space, $_SC;

    //允许上传类型
	$allowpictype = array('jpg','gif','png','jpeg');

	//检查
	$FILE['size'] = intval($FILE['size']);
	if(empty($FILE['size']) || empty($FILE['tmp_name']) || !empty($FILE['error'])) {
		return cplang('lack_of_access_to_upload_file_size');
	}
	
	//判断后缀
	$fileext = fileext($FILE['name']);
	if(!in_array($fileext, $allowpictype)) {
		return cplang('only_allows_upload_file_types');
	}

	//获取目录
	if(!$filepath = getfilepath($fileext, true)) {
		return cplang('unable_to_create_upload_directory_server');
	}

	//本地上传
	$new_name = $_SC['attachdir'].'./'.$filepath;
	$tmp_name = $FILE['tmp_name'];
	if(@copy($tmp_name, $new_name)) {
		@unlink($tmp_name);
	} elseif((function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name))) {
	} elseif(@rename($tmp_name, $new_name)) {
	} else {
		return cplang('mobile_picture_temporary_failure');
	}

	//检查是否图片
	if(function_exists('getimagesize') && !@getimagesize($new_name)) {
		@unlink($new_name);
		return cplang('only_allows_upload_file_types');
	}

	//缩略图
	include_once(S_ROOT.'./source/function_image.php');
	$thumbpath = wp_makethumb($new_name);
	$thumb = empty($thumbpath)?0:1;

	//是否压缩
	//获取上传后图片大小
	if(@$newfilesize = filesize($new_name)) {
		$FILE['size'] = $newfilesize;
	}

	//水印
	if($_SCONFIG['allowwatermark']) {
		makewatermark($new_name);
	}

	//入库
	//$file = $new_name.'.thumb.jpg';
	$file = $new_name;
	$_SGLOBAL['db']->query("UPDATE ".tname('mtag')."
			SET pic='$file'
			WHERE tagid='$profid'");
    return null;
}

//保存图片
function prof_pic_save($FILE, $tag1, $tag2, $title, $spotid=0) {
	global $_SGLOBAL, $_SCONFIG, $space, $_SC;

    //允许上传类型
	$allowpictype = array('jpg','gif','png','jpeg');

	//检查
	$FILE['size'] = intval($FILE['size']);
	if(empty($FILE['size']) || empty($FILE['tmp_name']) || !empty($FILE['error'])) {
		return cplang('lack_of_access_to_upload_file_size');
	}

	//判断后缀
	$fileext = fileext($FILE['name']);
	if(!in_array($fileext, $allowpictype)) {
		return cplang('only_allows_upload_file_types');
	}

	//获取目录
	if(!$filepath = getfilepath($fileext, true)) {
		return cplang('unable_to_create_upload_directory_server');
	}

    //相册选择
    $query = $_SGLOBAL['db']->query("SELECT albumid, albumname,friend FROM ".tname('album')." WHERE albumtype='1' AND uid='$_SGLOBAL[supe_uid]'");
    while($value = $_SGLOBAL['db']->fetch_array($query)) {
        $albums[] = $value;
    }

    if(count($albums) != 1)
	    return cplang('inadequate_capacity_space');

	//本地上传
	$new_name = $_SC['attachdir'].'./'.$filepath;
	$tmp_name = $FILE['tmp_name'];
	if(@copy($tmp_name, $new_name)) {
		@unlink($tmp_name);
	} elseif((function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name))) {
	} elseif(@rename($tmp_name, $new_name)) {
	} else {
		return cplang('mobile_picture_temporary_failure');
	}

	//检查是否图片
	if(function_exists('getimagesize') && !@getimagesize($new_name)) {
		@unlink($new_name);
		return cplang('only_allows_upload_file_types');
	}

	//缩略图
	include_once(S_ROOT.'./source/function_image.php');
	$thumbpath = makethumb($new_name);
	$thumb = empty($thumbpath)?0:1;

	//是否压缩
	//获取上传后图片大小
	if(@$newfilesize = filesize($new_name)) {
		$FILE['size'] = $newfilesize;
	}

	//水印
	if($_SCONFIG['allowwatermark']) {
		makewatermark($new_name);
	}

	//进行ftp上传
	if($_SCONFIG['allowftp']) {
		include_once(S_ROOT.'./source/function_ftp.php');
		if(ftpupload($new_name, $filepath)) {
			$pic_remote = 1;
			$album_picflag = 2;
		} else {
			@unlink($new_name);
			@unlink($new_name.'.thumb.jpg');
			runlog('ftp', 'Ftp Upload '.$new_name.' failed.');
			return cplang('ftp_upload_file_size');
		}
	} else {
		$pic_remote = 0;
		$album_picflag = 1;
	}
	
	//入库
	$title = getstr($title, 150, 1, 1, 1);

	//入库
	$setarr = array(
		'albumid' => $albums[0]['albumid'],
		'uid' => $_SGLOBAL['supe_uid'],
		'dateline' => $_SGLOBAL['timestamp'],
		'filename' => addslashes($FILE['name']),
		'postip' => getonlineip(),
		'title' => $title,
		'type' => addslashes($FILE['type']),
		'size' => $FILE['size'],
		'filepath' => $filepath,
		'thumb' => $thumb,
		'remote' => $pic_remote
	);
	$setarr['picid'] = inserttable('pic', $setarr, 1);

	//更新附件大小
	//积分
    updatespacestatus('get', 'prof_img');


	//相册更新
	if($albumid) {
		$file = $filepath.($thumb?'.thumb.jpg':'');
		$_SGLOBAL['db']->query("UPDATE ".tname('album')."
			SET picnum=picnum+1, updatetime='$_SGLOBAL[timestamp]', pic='$file', picflag='$album_picflag'
			WHERE albumid='$albumid'");
    }

    //入profpic库
	$psetarr = array(
		'picid' => $setarr['picid'],
		'profid' => $tag1,
		'uid' => $_SGLOBAL['supe_uid'],
		'dateline' => $_SGLOBAL['timestamp'],
		'postip' => getonlineip()
	);
	inserttable('profpic', $psetarr, 1);
    
    if($tag2)
    {
        $psetarr = array(
            'picid' => $setarr['picid'],
            'profid' => $tag2,
            'uid' => $_SGLOBAL['supe_uid'],
            'dateline' => $_SGLOBAL['timestamp'],
            'postip' => getonlineip()
        );
        inserttable('profpic', $psetarr, 1);
        if ($spotid) {
            $_SGLOBAL['db']->query("UPDATE ".tname('spot')." SET pic_cnt=pic_cnt+1, last_picid=".$setarr['picid']." WHERE spotid=".$spotid);
        }
    }

	//事件通知
	if($tag2){
		$mtag1=getprof($tag1);
		$mtag2=getprof($tag2);
		$fs = array();
		$fs['icon'] = 'spot';
		$fs['title_template'] = cplang('feed_spot_add_image');
		$fs['title_data'] = array(
				'tagname' => "<a href=\"site.php?ac=image&type=spot&id=$spotid\">$mtag1[tagname] 和 $mtag2[tagname]</a>"
			);
		$fs['body_template'] = '<b>{album}</b><br>';
		$pic_src = mkpicurl($setarr);
		$fs['body_data'] = array(
			'album' => "<a href=\"site.php?ac=image&type=spot&id=$spotid&picid=$setarr[picid]\"><img class=\"summaryimg\" alt=\"$title\" src=\"{$pic_src}\"></a>");
		$fs['body_general'] = '';
		$fs['target_ids'] = '$spotid';
	} else {
		$mtag1=getprof($tag1);
		$fs = array();
		$fs['icon'] = 'prof';
		$fs['title_template'] = cplang('feed_prof_add_image');
		$fs['title_data'] = array(
				'tagname' => "<a href=\"site.php?ac=profile&profid=$tag1\">$mtag1[tagname]</a>"
			);
		$fs['body_template'] = '<b>{album}</b><br>';
		$pic_src = mkpicurl($setarr);
		$fs['body_data'] = array(
			'album' => "<a href=\"site.php?ac=image&type=profile&id=$tag1&picid=$setarr[picid]\"><img class=\"summaryimg\" alt=\"$title\" src=\"{$pic_src}\"></a>");
		$fs['body_general'] = '';
		$fs['target_ids'] = '$tag1';
	}
	feed_add($fs['icon'], $fs['title_template'], $fs['title_data'], $fs['body_template'], $fs['body_data'], $fs['body_general'], null, null, $fs['target_ids']);
	return $setarr;
}


//加入profile
function profile_join($type, $key, $fieldid=0) {
	global $_SGLOBAL;
	
	//判断用户是否已经加入
	$havejoin = 0;
	$key = addslashes($key);
	
	if($type == 'tagid') {
		$wheresql = "main.tagid='$key'";
	} else {
		$wheresql = "main.tagname='$key' AND main.fieldid='$fieldid'";
	}
	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('mtag')." main WHERE $wheresql");
	if($mtag = $_SGLOBAL['db']->fetch_array($query)) {
		//判断是否加入
		$fieldid = $mtag['fieldid'];
		$havejoin = getcount('tagspace', array('tagid'=>$mtag['tagid'], 'uid'=>$_SGLOBAL['supe_uid']));
	}
	if($havejoin) {
		return $mtag;
	}
	
	$field = $_SGLOBAL['profield'][$fieldid];
	if(!$mtag) {
		if($type == 'tagid') return array();
		//创建
		$mtag = array(
			'tagname' => $key,
			'fieldid' => $fieldid
		);
		$tagid = inserttable('mtag', $mtag, 1);
		$mtag['membernum'] = 1;
		$mtag['tagid'] = $tagid;
	} else {
		$tagid = $mtag['tagid'];
	}
	
	//检查个数
	$mtag['title'] = $field['title'];
	
	//自己在当前栏目下面的群组
	$maxinputnum = 0;
	if($field['formtype'] == 'text') {
		$maxinputnum = intval($field['inputnum']);
	} elseif($field['formtype'] == 'select') {
		$maxinputnum = 1;
	}
	if($maxinputnum) {
		$query = $_SGLOBAL['db']->query("SELECT COUNT(*) FROM ".tname('tagspace')." ts, ".tname('mtag')." mtag 
			WHERE ts.tagid=mtag.tagid AND ts.uid='$_SGLOBAL[supe_uid]' AND mtag.fieldid='$fieldid'");
		$count = $_SGLOBAL['db']->result($query, 0);
		if($count >= $maxinputnum) {
			return array();
		}
	}
	
	//加入
	$setarr = array(
		'tagid' => $tagid,
		'uid' => $_SGLOBAL['supe_uid'],
		'username' => $_SGLOBAL['supe_username']
	);
	if($mtag['joinperm'] == 2) {
		return array();
	} elseif($mtag['joinperm'] == 1) {
		$mtag['grade'] = $setarr['grade'] = -2;//需要审核
	} else {
		//检测是否有群主
		$query = $_SGLOBAL['db']->query("SELECT COUNT(*) FROM ".tname('tagspace')." WHERE tagid='$tagid' AND grade>=8");
		$modcount = $_SGLOBAL['db']->result($query, 0);
		if($modcount) {
			$mtag['grade'] = $setarr['grade'] = 0;//已经有群主
		} else {
			$mtag['grade'] = $setarr['grade'] = $field['manualmoderator']?0:9;//自动为群主
		}
		//事件通知
		$fs = array();
		$fs['icon'] = 'prof';
		$fs['title_template'] = cplang('feed_prof_join');
		$fs['title_data'] = array(
				'mtag' => "<a href=\"site.php?ac=prof&profid=$tagid\">$mtag[tagname]</a>",
				'field' => "<a href=\"site.php?ac=show&fid=$mtag[fieldid]\">$mtag[title]</a>"
			);
		$fs['target_ids'] = "$tagid";
		if(ckprivacy('mtag', 1)) {
			feed_add($fs['icon'], $fs['title_template'], $fs['title_data'], null, null, null, null, null, $fs['target_ids']);
		}
	}
	if($setarr) {
		$_SGLOBAL['db']->query("UPDATE ".tname('mtag')." SET membernum=membernum+1 WHERE tagid='$tagid'");
		inserttable('tagspace', $setarr, 0, true);
	}
	return $mtag;
}

//退出profile
function profile_out($mtag, $uids) {
	global $_SGLOBAL;

	$_SGLOBAL['db']->query("DELETE FROM ".tname('tagspace')." WHERE tagid='$mtag[tagid]' AND uid IN (".simplode($uids).")");
	//更新成员数
	$count = getcount('tagspace', array('tagid'=>$mtag['tagid']));
	if($count > 0) {
		updatetable('mtag', array('membernum'=>$count), array('tagid'=>$mtag['tagid']));
	} else {
		//解散
		//include_once(S_ROOT.'./source/function_delete.php');
		//deletemtag(array($mtag['tagid']));
	}
}

//加入
function create_profile($type, $key, $fieldid=0) {
	global $_SGLOBAL;
	
	//判断用户是否已经加入
	$havejoin = 0;
	$key = addslashes($key);
	
	if($type == 'tagid') {
		$wheresql = "main.tagid='$key'";
	} else {
		$wheresql = "main.tagname='$key' AND main.fieldid='$fieldid'";
	}
	
    $query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('mtag')." main WHERE $wheresql");
	if($mtag = $_SGLOBAL['db']->fetch_array($query)) {
        if ($mtag['tagtype']) {
            //判断是否存在
            return $mtag;
        }
	}
	
	$field = $_SGLOBAL['profield'][$fieldid];
	if(!$mtag) {
		if($type == 'tagid') return array();
		//创建
		$mtag = array(
			'tagname' => $key,
            'fieldid' => $fieldid,
            'tagtype' => '1'
		);
		$tagid = inserttable('mtag', $mtag, 1);
		$mtag['membernum'] = 1;
		$mtag['tagid'] = $tagid;
	} else {
		$tagid = $mtag['tagid'];
	}
	
	//检查个数
	$mtag['title'] = $field['title'];
	
	//加入
	$setarr = array(
		'tagid' => $tagid,
		'uid' => $_SGLOBAL['supe_uid'],
		'username' => $_SGLOBAL['supe_username']
	);
	/*
	if($mtag['joinperm'] == 2) {
		return array();
	} elseif($mtag['joinperm'] == 1) {
		$mtag['grade'] = $setarr['grade'] = -2;//需要审核
	} else {*/
		//检测是否有群主
		$query = $_SGLOBAL['db']->query("SELECT COUNT(*) FROM ".tname('tagspace')." WHERE tagid='$tagid' AND grade>=8");
		$modcount = $_SGLOBAL['db']->result($query, 0);
		if($modcount) {
			$mtag['grade'] = $setarr['grade'] = 0;//已经有群主
		} else {
			$mtag['grade'] = $setarr['grade'] = $field['manualmoderator']?0:9;//自动为群主
		}
		//事件通知
		$fs = array();
		$fs['icon'] = 'prof';
		$fs['title_template'] = cplang('feed_prof_create');
		$fs['title_data'] = array(
				'tagname' => "<a href=\"site.php?ac=profile&op=index&profid=$tagid\">$mtag[tagname]</a>",
				'field' => "<a href=\"site.php?ac=show&fid=$mtag[fieldid]\">$mtag[title]</a>"
			);
		$fs['target_ids'] = "$tagid";
		//if(ckprivacy('mtag', 1)) {
			feed_add($fs['icon'], $fs['title_template'], $fs['title_data'], null, null, null, null, null, $fs['target_ids']);
		//}
	//}
	if($setarr) {
		$_SGLOBAL['db']->query("UPDATE ".tname('mtag')." SET membernum=membernum+1 WHERE tagid='$tagid'");
		inserttable('tagspace', $setarr, 0, true);
	}
    updatespacestatus('get', 'prof'); 
	return $mtag;
}

function note_apply($sqlarr) {
	global $_SGLOBAL;
	
	$fieldsql = $comma = '';
	if(is_array($sqlarr)) {
		$uids = array();
		$valsql = '(';
		foreach($sqlarr as $key => $value) {
			$uids[] = $value['uid'];
			foreach($value as $vkey => $val) {
				if($key == 0) {
					$fieldsql .= $comma.$vkey;
				}
				$valsql .= $comma.'\''.$val.'\'';
				$comma = ', ';
			}
			if(count($sqlarr)-1 > $key) {
				$valsql .= '), (';
				$comma = '';
			}
		}
		$valsql .= ')';
		$_SGLOBAL['db']->query('insert into '.tname('notification').' ('.$fieldsql.') values '.$valsql);
		$_SGLOBAL['db']->query("UPDATE ".tname('space')." SET notenum=notenum+1 WHERE uid IN (".simplode($uids).")");
	}
}

// the four functions will compact into one.
function getprofspotcnt($profid) {
    global $_SGLOBAL;

    $sql = "SELECT count(*) FROM (select DISTINCT a.* from ".tname('mtag')." a left join ".tname('spot')." b on a.tagid = b.tag1 or a.tagid = b.tag2
                 where a.tagid <> $profid and (b.tag1 = $profid or b.tag2 = $profid)) AS count";

 
    $result = $_SGLOBAL['db']->result($_SGLOBAL['db']->query($sql), 0);

    return $result ? $result : 0;
}

function getprofthreadcnt($profid) {
    global $_SGLOBAL;

    $sql = "SELECT count(*) FROM ".tname('thread')." 
            WHERE tagid='$profid'";


    $result = $_SGLOBAL['db']->result($_SGLOBAL['db']->query($sql), 0);

    return $result ? $result : 0;
}

function getproffancnt($profid) {
    $result = getcount('tagspace', array('tagid'=>$profid));

    return $result ? $result : 0;
}

function getprofpiccnt($profid) {
    global $_SGLOBAL;

    $sql =  "SELECT count(*) FROM (SELECT DISTINCT p.* FROM ".tname('profpic')." pp, ".tname('pic')." p WHERE pp.profid=".$profid." AND p.picid = pp.picid ORDER BY p.dateline DESC) AS count";

    $result = $_SGLOBAL['db']->result($_SGLOBAL['db']->query($sql), 0);

    return $result ? $result : 0;
}

function getprofieldtxtbyfid($fid = 0) {
	global $_SGLOBAL;

	foreach($_SGLOBAL['profield'] as $value) {
		if ($value['fieldid'] == $fid)
			return $value['title'];
	}

	return null;
}

?>
